package com.loongtech.bi.action.newsystem;

import com.loongtech.bi.dao.CommonDao;
import com.loongtech.bi.entity.system.EntitySyncInfoLog;
import com.loongtech.bi.manager.system.SyncInfoLogManager;
import com.loongtech.bi.manager.system.SyncSysConfigManager;
import com.loongtech.core.util.Time;
import com.loongtech.core.util.Utils;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: yuri
 * Description: 系统配置同步接口
 * Date: 16:36 2017/7/21
 */
@RestController
@Scope("prototype")
@RequestMapping("/configSync")
public class SyncSysConfigAction {
    @Resource
    private SyncSysConfigManager syncSysConfigManager;
    @Resource
    private SyncInfoLogManager syncInfoLogManager;
    @Resource(name = "commonDao")
    private CommonDao commonDao;

    //true-成功
    @RequestMapping(value = "sync.do", method = {RequestMethod.GET, RequestMethod.POST})
    public Boolean syncToDatabase(@RequestParam String sql) {
        Integer res;
        try {
            res = syncSysConfigManager.excuteBySql(sql);
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return !(res == null);
    }

    public void callsyncToDatabase() {
        try {
            List<EntitySyncInfoLog> list = commonDao.queryObjList("select a.* ,b.projectUrl from syncinfo_log a, system_project b where a.gameId = b.id and a.status = 0", null, EntitySyncInfoLog.class);
            Map<String, Object> params = new HashMap<>();
            for (EntitySyncInfoLog entity : list) {
                String url = entity.getProjectUrl() + "/configSync/sync.do";
                params.put("sql", entity.getExcuteSql());
                System.out.println("系统配置推送地址为:" + url);
                String res = Utils.httpPost(url, params);
                System.out.println("系统配置推送返回值为" + res);
                if ("false".equals(res)) {
                    continue;
                }
                entity.setStatus(1);
                entity.setFinishTime(Time.currentTime());
                syncInfoLogManager.merge(entity);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
